package controllers;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import models.Product;
import play.Logger;
import play.Play;
import play.mvc.Controller;

public class OnceProcess extends Controller {

	private static final String fileFolder = Play.configuration.getProperty("attachments.path");
	
	public static String removeHtmlTag(){
		List<Product> products = Product.all().fetch();
		for (Product product : products) {
			product.summary = product.summary.
			replaceAll("\\&[a-zA-Z]{1,10};", "")
			.replaceAll("<[^>]*>", "")
			.replaceAll("[(/>)<]", "");
			product.save();
		}
		return "successful";
	}
	
	public static String renameImages(){
		List<Product> products = Product.all().fetch();
		for (Product product : products) {
			product.detailImage = renameFile(product.detailImage);
			product.homepageBigImage = renameFile(product.homepageBigImage);
			product.homepageSmallImage = renameFile(product.homepageSmallImage);
			product.brochure = renameFile(product.brochure);
			if(product.images!=null && product.images.size()>0){
				ArrayList<String> images = new ArrayList<String>();
				for (String image : product.images) {
					images.add(renameFile(image));
				}
				product.images = images;
			}
			product.save();
			Logger.info("product updated %s", product.id);
		}
		return "ok";
	}
	
	private static String renameFile(String fileName){
		if(StringUtils.isEmpty(fileName)){
			return "";
		}
		File file = new File(fileFolder,fileName);
		if(!file.exists()){
			return "";
		}
		String newName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS");
		newName += RandomStringUtils.randomNumeric(4);
		String extension = FilenameUtils.getExtension(fileName);
//		String extension = "jpg";
		newName += "." + extension;
		file.renameTo(new File(fileFolder,newName));
		return newName;
	}
}
